package com.naizhuai;

import android.app.Application;
import android.content.SharedPreferences;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.SharedPreferenceUtil;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.AlbumLoader;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;


import cn.jpush.android.api.JPushInterface;

/**
 * Created by code_han on 2018/2/22.
 */

public class AppContext extends Application {

    public static AppContext app;
    public static String registrationID;

    public AppContext() {
        app = this;
    }

    public static synchronized AppContext getInstance() {

        return app;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        JPushInterface.init(this);
        /*
        参数1：isManual 用户手动点击检查，非用户点击操作请传false
        参数2：isSilence 是否显示弹窗等交互，[true:没有弹窗和toast] [false:有弹窗或toast]
         */
//        Beta.checkUpgrade(false, false);
        Beta.autoCheckUpgrade = false;
        Bugly.init(getApplicationContext(), "f4df7d3bb9", true);
        registrationID = JPushInterface.getRegistrationID(this);
        NaizhuAILog.d("getRegistrationID:  " + registrationID);
        Album.initialize(AlbumConfig.newBuilder(this).setAlbumLoader(new AlbumLoader() {
            @Override
            public void loadAlbumFile(ImageView imageView, AlbumFile albumFile, int viewWidth, int viewHeight) {
                load(imageView, albumFile.getPath());
            }

            @Override
            public void loadImage(ImageView imageView, String imagePath, int viewWidth, int viewHeight) {
                load(imageView, imagePath);
            }
        }).build());
//        registerUncaughtExceptionHandler();

    }

    public void load(ImageView imageView, String url) {
        Glide.with(imageView.getContext())
                .load(url)
                .error(R.mipmap.wrong_image_icon)
                .placeholder(R.mipmap.wrong_image_icon)
                .crossFade()
                .into(imageView);
    }

    // 注册App异常崩溃处理器
    private void registerUncaughtExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());
    }

    @CheckResult
    public static <T> T getSpValue(String keyword, @NonNull T t) {
        return SharedPreferenceUtil.getInstance(app).getValue(keyword, t);
    }

    public static <T> boolean setSpValue(String keyword, T t) {
        return SharedPreferenceUtil.getInstance(app).saveValue(keyword, t);
    }

    public static SharedPreferences.Editor getEditor() {
        return SharedPreferenceUtil.getInstance(app).getEditor();
    }

}
